﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Fixx.DTO;

namespace Fixx.Connector
{
	internal class FixxMultiConnectionState
	{
		public Action<FixxStatus> SuccessCallback { get; set; }
		public string EndPoint { get; set; }
	}
	class FixxMultiConnection
	{
		private Dictionary<IFixxConnection, FixxMultiConnectionState> Connections { get; set; }
		private IFixxSettings _FixxSettings { get; set; }
		private Action _Success { get; set; }
		private Action _Fail { get; set; }

		public FixxMultiConnection(IFixxSettings settings)
        {
            this._FixxSettings = settings;
        }
		public bool HasPendingConnections()
		{
			return (this.Connections != null && this.Connections.Count > 0);
		}
		public void AppendGetConnectionTo(string endpoint, Action<string> success)
		{
			FixxConnection connection = new FixxConnection(this._FixxSettings);
			var state = new FixxMultiConnectionState()
			{
				EndPoint = endpoint,
				SuccessCallback = (status) =>
				{
					success(status.Result);
					this.Connections.Remove(connection);
					if (this.Connections.Count == 0)
					{
						this._Success();
					}
				}
			};
			if (this.Connections == null)
				this.Connections = new Dictionary<IFixxConnection, FixxMultiConnectionState>();
			this.Connections.Add(connection, state);

		}
		public void Begin(Action hSuccess, Action hFailure)
		{
			this._Success = hSuccess;
			this._Fail = hFailure;

			foreach (var c in this.Connections)
			{
				var connection = c.Key;
				var state = c.Value;
				connection.Get(state.EndPoint, state.SuccessCallback);
			}
		}
	}
}
